//
//  mmjMeFootView.m
//  Social
//
//  Created by seirra on 2018/5/16.
//  Copyright © 2018年 mmj. All rights reserved.
//

#import "mmjMeFootView.h"
#import <AFNetworking.h>
#import <MJExtension.h>
#import <UIImageView+WebCache.h>
#import <UIButton+WebCache.h>
#import <SafariServices/SafariServices.h>
@implementation mmjMeFootView
-(NSMutableDictionary<NSString *,mmjMeSquare *> *)allSquares{
    if (!_allSquares) {
                _allSquares = [NSMutableDictionary dictionary];
            }
    return _allSquares;
}
-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        //self.backgroundColor = [UIColor whiteColor];
        NSMutableDictionary * params =[NSMutableDictionary dictionary];
        //参数
        params[@"a"] = @"square";
        params[@"c"] = @"topic";
        //获得缓存路径
        NSString * cachepath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSString* dirpath = [cachepath stringByAppendingPathComponent:@"me.plist"]; //拼接路径
        //请求
        [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary*  _Nullable responseObject) {
            [responseObject writeToFile:/*@"//Users/hack/Desktop/me.plist"*/dirpath atomically:YES];
            //mmjLog(@"请求成功success %@",responseObject);
            
            
            NSArray *squares = [mmjMeSquare mj_objectArrayWithKeyValuesArray:responseObject[@"square_list"] ];
            
           // mmjLog(@"%@",squares);
            [self creatsquares:squares];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //mmjLog(@"请求失败error %@",error);
        }];
        
    }
    return self;
}
-(void)creatsquares:(NSArray *)squares{
    // 方块个数
    NSInteger count = squares.count;
    //方块尺寸
    int maxcolscount = 4;         //一行4列
    CGFloat buttonW = self.mmj_width / maxcolscount;
    CGFloat buttonH = buttonW;
    //创建所有的方块
    
    for (NSInteger i = 0; i<count; i++) {
        //i位置对应的模型数据
        mmjMeSquare *square = squares[i];
        
        //创建按钮
        mmjMeSquareButton* button = [mmjMeSquareButton buttonWithType:UIButtonTypeCustom];

        [self addSubview:button];
        [button addTarget:self action:@selector(buttonclick:) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        //设置frame
        button.mmj_x = (i % maxcolscount) * buttonW;
        button.mmj_y =(i / maxcolscount) * buttonH ;
        button.mmj_height =buttonH ;
        button.mmj_width =buttonW ;
//        button.mmj_height =buttonH-1 ;
//        button.mmj_width =buttonW-1 ;
        //设置数据
        button.backgroundColor = [UIColor whiteColor];
        [button setTitle:square.name forState:UIControlStateNormal];
        //设置图片
        [button sd_setImageWithURL:[NSURL URLWithString:square.icon] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"setup-head-default"]];
       
        
        // 存储模型数据
                self.allSquares[button.currentTitle] = square;
        
    }
    
    //根据行数计算设置footview的高度
    //总数
//    NSInteger rowcount = 0;
//    if (count % maxcolscount == 0) {
//        rowcount = count/maxcolscount;
//    }
//    else{
//         rowcount = count/maxcolscount;
//        rowcount = rowcount+1;
//    }
    
    NSInteger rowcount = (count + maxcolscount - 1)/maxcolscount;//公式：（总数量 + 每一行最大数量-1）/每一行最大数量
    self.mmj_height = rowcount * buttonH;
    
    //设置footview的高度 == 最后一个button的bottom
//    self.mmj_height = self.subviews.lastObject.mmj_bottom;

    
    UITableView* tableview = (UITableView *)self.superview;
    tableview.tableFooterView = self;
    [tableview reloadData];
//    tableview.contentSize = CGSizeMake(0, self.mmj_bottom);
}
-(void)buttonclick:(mmjMeSquareButton*)button{
    mmjMeSquare*square = self.allSquares[button.currentTitle];
    NSString* url = square.url;
    if ([square.url hasPrefix:@"http"]) {//用webview加载url
        
//        mmjWebViewController * webview= [[mmjWebViewController alloc]init];
//        webview.url = url;
//        webview.navigationItem.title = square.name;
//        UITabBarController * tabbarvc = (UITabBarController *)self.window.rootViewController;
//        UINavigationController* nav = tabbarvc.childViewControllers.firstObject;
//        [nav pushViewController:webview animated:YES];
        
        
        SFSafariViewController * webview = [[SFSafariViewController alloc]initWithURL:[NSURL URLWithString:url]];
        UITabBarController * tabbarvc = (UITabBarController *)self.window.rootViewController;
        [tabbarvc presentViewController:webview animated:YES completion:nil];
        
        
        
    }
    else if ([square.url hasPrefix:@"mod"]){
        if ([square.url hasSuffix:@"BDJ_To_HuaXiReader"]) {
            mmjLog(@"123");
        }
        else
            mmjLog(@"789");
    }
    else{
        mmjLog(@"456");
    }
}
@end
